package com.zsw.talk;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Client {
	
	private final static Logger LOG = LoggerFactory.getLogger(Client.class);
	static final boolean SSL = System.getProperty("ssl") != null;
    static final String HOST = System.getProperty("host", "127.0.0.1");
    static final int PORT = Integer.parseInt(System.getProperty("port", SSL ? "8992" : "8899"));
    static final int SIZE = Integer.parseInt(System.getProperty("size", "256"));
    final static JTextArea J_TEXT_AREA = new JTextArea(8,25);
    
    public static void main(String[] args) throws Exception {
    	Client client = new Client();
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
             .channel(NioSocketChannel.class)
             .option(ChannelOption.TCP_NODELAY, true)
             .handler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 public void initChannel(SocketChannel ch) throws Exception {
                     ch.pipeline().addLast(
                    		 new StringEncoder(CharsetUtil.UTF_8),
                    		 new StringDecoder(CharsetUtil.UTF_8),
//                             new LineBasedFrameDecoder(8192),
//                             new ChunkedWriteHandler(),
//                    		 new LoggingHandler(LogLevel.WARN),
                    		 new ClientHandler());
                 }
             });
            Channel ch = b.connect(HOST, PORT).sync().channel();
            LOG.info("Start talk,please enter some text (quit to end).");
            client.jFrame(group, ch);
        } finally {
            group.shutdownGracefully();
        }
    }
	public void jFrame(EventLoopGroup group, Channel ch) throws IOException {
		JFrame jFrame = new JFrame("Hello");
		jFrame.setLayout(new FlowLayout());
		jFrame.setSize(300, 250);
		jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		jFrame.setLocationRelativeTo(null);
		jFrame.setResizable(false);
		jFrame.addWindowListener(new WindowAdapter(){
			public void windowClosing(WindowEvent e) {
				ch.disconnect();
				ch.close();
				group.shutdownGracefully();
				System.exit(-1);
			}
		});
		J_TEXT_AREA.setEditable(false);
		J_TEXT_AREA.setWrapStyleWord(true);
		J_TEXT_AREA.setLineWrap(true);
		JScrollPane jScrollPane = new JScrollPane(J_TEXT_AREA);
		jScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		JTextField jTextField = new JTextField(25);
		jTextField.addKeyListener(new KeyListener() {
			@Override
			public void keyTyped(KeyEvent e) {}
			@Override
			public void keyPressed(KeyEvent e) {}
			@Override
			public void keyReleased(KeyEvent e) {
				if(e.getKeyCode() == 10){
					send(ch, jTextField);
				}
			}
		});
		JButton jButton0 = new JButton("发送");
		jButton0.setSize(100, 50);
		jButton0.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				send(ch, jTextField);
			}
		});
		JButton jButton1 = new JButton("关闭");
		jButton1.setSize(100, 50);
		jButton1.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				ch.disconnect();
				ch.close();
				group.shutdownGracefully();
				System.exit(-1);
			}
		});
		jFrame.add(jScrollPane);
		jFrame.add(jTextField);
		jFrame.add(jButton0);
		jFrame.add(jButton1);
		jFrame.setVisible(true);
		jTextField.requestFocus();
		ChannelFuture lastWriteFuture = null;
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        for (;;) {
            String line = in.readLine();
            if (line == null || "quit".equalsIgnoreCase(line)) {
                break;
            }
            lastWriteFuture = ch.writeAndFlush(line);
        }
        if (lastWriteFuture != null) {
            lastWriteFuture.awaitUninterruptibly();
        }
	}
	private void send(Channel ch, JTextField jt) {
		String line = jt.getText();
		if(line.length() > 0){
			ch.writeAndFlush(line);
			jt.setText("");
			jt.requestFocus();
			J_TEXT_AREA.setText((J_TEXT_AREA.getText().equals("") ? "" : (J_TEXT_AREA.getText()+ "\r\n")) + "This :"+ line);
		}
	}
	public static void showRecivedMsg(String body){
		J_TEXT_AREA.setText((J_TEXT_AREA.getText().equals("") ? "" : (J_TEXT_AREA.getText()+ "\r\n")) + "That :"+ body);
        J_TEXT_AREA.setCaretPosition(J_TEXT_AREA.getDocument().getLength());
	}
}
